from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework import filters
from rest_framework.views import APIView
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .models import imageInfo
from .models import push_log
from .serializers import ImageDetailSerializer
from .serializers import ImageHistoryPushRecordSerializer
from libs.paginations import ListPagination
from .utils.image_push import Image_Push_opration


class ImageViewSet(viewsets.GenericViewSet,
                   mixins.ListModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.DestroyModelMixin):
    '''
    获取镜像信息
    删除镜像信息
    '''
    queryset = imageInfo.objects.all()
    serializer_class = ImageDetailSerializer
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    pagination_class = ListPagination
    filter_backends = (filters.SearchFilter, filters.OrderingFilter,DjangoFilterBackend)
    filter_fields = ('application_type',)
    search_fields = ("name",)


class ImageHistoryPushRecord(viewsets.GenericViewSet,
                             mixins.ListModelMixin):
    '''推送镜像历史记录'''

    queryset = push_log.objects.all()
    serializer_class = ImageHistoryPushRecordSerializer
    pagination_class = ListPagination
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_search = ('name',)
    filter_fields = ('application_type', 'push_env', 'name')


class ImageOpration(APIView):
    '''推送镜像  传参: {'id_list':arry,'remote_env':str} ，id_list为每条记录的id，env为推送的目标环境'''

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def post(self, request, *args, **kwargs):

        # id_arry = self.request.data.getlist('id_list')
        id_arry = self.request.data.get('id_list')
        remote_env = self.request.data.get('remote_env')
        image_pushing = Image_Push_opration(id_list=id_arry, remote_env=remote_env)
        return Response(image_pushing.push_opration(self.request.user))